﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;

namespace Inicio.Core.Repositories
{
    public class SearchRepository
    {
        public DataTable SearchInDB(string qry, FlowLayoutPanel pnlControls)//, string op)
        {
            ucSearchField uc;

            foreach (Control ctl in pnlControls.Controls)
            {
                if (ctl is ucSearchField && ((ucSearchField)ctl).Value != null)
                {
                    uc = (ucSearchField)ctl;

                    if (uc.Field.Control == "TextBox")
                        qry += " AND WORK." + uc.Field.FilterField + " LIKE '%" + Convert.ToString(uc.Value) + "%'";

                    else if (uc.Field.Control == "ComboBox")
                        qry += " AND WORK." + uc.Field.FilterField + " = " + Convert.ToString(uc.Value);

                    else if (uc.Field.Control == "NumericBox")
                        qry += " AND SPOUT." + uc.Field.FilterField + " " + Convert.ToString(((ucSearchField)(ctl)).cbOperator.Text) + Convert.ToString(uc.Value);
                }
            }

            return GetTable(qry);
        }

        private DataTable GetTable(string qry)
        {
            DataTable dt = new DataTable();

            using (SqlCeConnection cn = new SqlCeConnection(Core.Connection.conec))
            {
                using (SqlCeDataAdapter da = new SqlCeDataAdapter(qry, cn))
                {
                    da.Fill(dt);
                }
            }
            return dt;
        }
    }
}
